#!/bin/bash
set -e

MOUNT_POINT=arm64/rootfs
ROOTFS=qemu/rootfs.ext2
IMG=qemu/rootfs.img
APP_PATH=build/bin
LIB_PATH=build/lib
INSTALL_PATH=build/install
TARGET_PATH=/usr/bin
TARGET_LIB_PATH=/usr/lib
WORKSPACE=/workspace

expand_ext2_image() {
  local ROOTFS="$1"
  local EXPAND_MB="${2:-100}"  # 默认扩容 100MB    
  # 获取文件大小（单位：字节）
  SIZE=$(stat -c%s "$ROOTFS")
  # 100MB = 100 * 1024 * 1024 字节
  LIMIT=$((100 * 1024 * 1024))
  if [ "$SIZE" -gt "$LIMIT" ]; then
    echo "文件大小超过 100MB:$FILE($SIZE 字节）"
  else
    echo "文件大小在限制范围内：$FILE($SIZE 字节）"
    echo "向镜像追加 ${EXPAND_MB}MB 空白空间..."
    sudo dd if=/dev/zero bs=1M count="$EXPAND_MB" >> "$ROOTFS"
  
    echo "检查 ext2 文件系统完整性..."
    sudo e2fsck -f "$ROOTFS"
  
    echo "扩展 ext2 文件系统结构..."
    sudo resize2fs "$ROOTFS"
  
    echo "扩容完成：$ROOTFS"
  fi
}

inject_app(){
  # 创建挂载点
  echo "创建挂载点：$MOUNT_POINT"
  sudo mkdir -p "$MOUNT_POINT"
  
  # 挂载镜像
  echo "挂载镜像：$IMG 到 $MOUNT_POINT"
  sudo mount -o loop "$IMG" "$MOUNT_POINT"
  
  # 创建目标目录（如果不存在）
  #echo "创建目标目录：$MOUNT_POINT$TARGET_PATH"
  #sudo mkdir -p "$MOUNT_POINT$TARGET_PATH"
  
  # 拷贝可执行文件
  #echo "拷贝可执行文件：$APP_PATH -> $MOUNT_POINT$TARGET_PATH/"
  #sudo cp "$APP_PATH/*" "$MOUNT_POINT$TARGET_PATH/"
  
  #echo "拷贝库文件：$LIB_PATH -> $MOUNT_POINT$TARGET_LIB_PATH/"
  #sudo cp "$LIB_PATH/*" "$MOUNT_POINT$TARGET_LIB_PATH/"
  
  echo "删除rootfs中的目录:$MOUNT_POINT$WORKSPACE"
  sudo rm -r "$MOUNT_POINT$WORKSPACE/"
  
  echo "拷贝安装目录：$INSTALL_PATH -> $MOUNT_POINT$WORKSPACE/"
  sudo cp -ra "$INSTALL_PATH" "$MOUNT_POINT$WORKSPACE/"
  sudo cp -a "scripts/run-app.sh" "$MOUNT_POINT$WORKSPACE/"
  
  # 卸载镜像
  echo "卸载挂载点：$MOUNT_POINT"
  sudo umount "$MOUNT_POINT"
  
  # 删除挂载点
  echo "卸载挂载点：$MOUNT_POINT"
  sudo rm -rf "$MOUNT_POINT"
}

expand_ext2_image $ROOTFS
inject_app

